import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import { NzTableModule } from 'ng-zorro-antd/table';

enum SelectStatus {
  All = -1,
  None = 0,
  Partial = 2,
}
export interface Data {
  id: number;
  name: string;
  age: number;
  address: string;
  disabled: boolean;
}

interface CheckableData extends Data {
  checked?: boolean;
}

const items = new Array(100).fill(0).map(
  (_, index) =>
    ({
      id: index,
      name: `Edward King ${index}`,
      age: 32,
      address: `London, Park Lane no. ${index}`,
      disabled: index % 2 === 0,
    } as CheckableData)
);

@Component({
  selector: 'app-table-row-selection',
  standalone: true,
  imports: [NzTableModule, CommonModule],
  templateUrl: './table-row-selection.component.html',
  styleUrl: './table-row-selection.component.less',
})
export class TableRowSelectionComponent {
  readonly listOfData = items;
  listOfCurrentPageData: readonly CheckableData[] = [];

  private _selectStatus = SelectStatus.None;

  get allIndeterminate() {
    return this._selectStatus === SelectStatus.Partial;
  }

  get allChecked() {
    return this._selectStatus === SelectStatus.All;
  }

  private get currentEnableData() {
    return this.listOfCurrentPageData.filter((item) => !item.disabled);
  }

  get selectedCount() {
    return this.listOfData.filter((item) => item.checked).length;
  }

  private refreshAllCheckState() {
    const items = this.currentEnableData;
    if (items.every((item) => item.checked)) {
      this._selectStatus = SelectStatus.All;
    } else if (items.every((item) => !item.checked)) {
      this._selectStatus = SelectStatus.None;
    } else {
      this._selectStatus = SelectStatus.Partial;
    }
  }

  onPageChange(items: readonly CheckableData[]) {
    this.listOfCurrentPageData = items;
    this.refreshAllCheckState();
  }

  onAllCheckChange(checked: boolean) {
    this.currentEnableData.forEach((item) => (item.checked = checked));
    this.refreshAllCheckState();
  }

  onItemCheckChange(item: CheckableData, checked: boolean) {
    item.checked = checked;
    this.refreshAllCheckState();
  }
}
